package com.gzdh.tang.dishrecognition.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gzdh.tang.comm.constant.SpringContextUtils;
import com.gzdh.tang.comm.util.GZip;
import com.gzdh.tang.comm.util.ObjectUtil;
import com.gzdh.tang.comm.vo.Result;
import com.gzdh.tang.dishrecognition.dto.WeekMenuBakDto;
import com.gzdh.tang.dishrecognition.entity.MacMainpFoodMenu;
import com.gzdh.tang.dishrecognition.mapper.DrPublicMapper;
import com.gzdh.tang.dishrecognition.model.BmcmListRes;
import com.gzdh.tang.dishrecognition.model.BmzlListRes;
import com.gzdh.tang.dishrecognition.service.MacMainpFoodMenuService;
import com.gzdh.tang.mobile.entity.Bmcm;
import com.gzdh.tang.mobile.service.BmcmService;
import com.gzdh.tang.modu.entity.*;
import com.gzdh.tang.modu.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("dr/down")
public class DrDownController {

    @Autowired
    BmcmService bmcmService;

    @Autowired
    BmzlService bmzlService;

    @Autowired
    BqService bqService;

    @Autowired
    KsService ksService;

    @Autowired
    TangDeviceService tangDeviceService;

    @Autowired
    MacMainpSbruanService macMainpSbruanService;

    @Autowired
    MacMainpSbruanDinnerService macMainpSbruanDinnerService;

    @Autowired
    ZweekmenubakService zweekmenubakService;

    @Autowired
    DrPublicMapper drPublicMapper;
    @Autowired
    FkService fkService;

    @Autowired
    MacMainpFoodMenuService macMainpFoodMenuService;

    @PostMapping("getFk")
    public Result<Object> getFk(@RequestBody JSONObject reqJson) {
        Result<Object> result = new Result<>();
        System.out.println("开始下载白名单" + reqJson.toString());
        JSONObject jsonObject = new JSONObject();
        String deviceId = reqJson.getString("deviceId");
        MacMainpSbruan macMainpSbruan = macMainpSbruanService.getOne(new QueryWrapper<MacMainpSbruan>()
                .lambda().eq(MacMainpSbruan::getMac, deviceId));
        List<Fk> ifkPage = fkService.getFkByPage(reqJson.getInteger("pageNum"),
                reqJson.getInteger("pageSize"), macMainpSbruan.getId());
        jsonObject.put("fk", ifkPage);
        jsonObject.put("count", fkService.getCount(macMainpSbruan.getId()));
        result.setResult(GZip.gzip(jsonObject.toString()));
        return result;
    }

    /**
     * 下载餐次
     *
     * @return
     */
    @GetMapping("getBaseSysInfo")
    public Result<Object> getBaseSysInfo(@RequestParam("userId") String userId,
                                         @RequestParam("deviceId") String deviceId) {
        Result<Object> result = new Result<>();
        JSONObject jsonObject = new JSONObject();

        //下载一周菜谱
        MacMainpSbruan macMainpSbruan = macMainpSbruanService.getOne(new QueryWrapper<MacMainpSbruan>().lambda()
                .eq(MacMainpSbruan::getMac, deviceId));

        //下载餐次
        List<Bmcm> bmcmList = bmcmService.list();
        List<BmcmListRes> bmcmListResList = new ArrayList<>();
        for (Bmcm goo : bmcmList) {
            BmcmListRes bmcmListRes1 = new BmcmListRes();
            bmcmListRes1.setBm(goo.getBm().trim());
            bmcmListRes1.setName(goo.getName());
            bmcmListRes1.setBeginTime(goo.getBegintime());
            bmcmListRes1.setEndTime(goo.getEndtime());
            bmcmListResList.add(bmcmListRes1);
        }
        jsonObject.put("bmcm", bmcmListResList);

        //下载灶类
        Environment environment = SpringContextUtils.getApplicationContext().getEnvironment();
        Boolean useZlAddr = environment.getProperty("database.queryTableNameContainsAddr.bmzl", Boolean.class);
        List<Bmzl> bmzlList;
        if(useZlAddr != null && useZlAddr) {
            bmzlList = bmzlService.selectListByTableNameContainAddr(ObjectUtil.getStr(macMainpSbruan.getAddr()));
        } else {
            bmzlList = bmzlService.list();
        }
        List<BmzlListRes> bmzlListResList = new ArrayList<>();
        for (Bmzl goo : bmzlList) {
            BmzlListRes bmzlListRes = new BmzlListRes();
            bmzlListRes.setBm(goo.getBm().trim());
            bmzlListRes.setName(goo.getName());
            bmzlListResList.add(bmzlListRes);
        }
        jsonObject.put("bmzl", bmzlListResList);

        //下载病区
        List<Bq> bqList = bqService.queryList();
        jsonObject.put("bq", bqList);

        //下载科室
        List<Ks> ksList = ksService.queryList();
        jsonObject.put("ks", ksList);

        List<MacMainpFoodMenu> foodMenuList = new LinkedList<>();
        try {
            String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

            Map<String, Object> valuesMap = new HashMap();
            valuesMap.put("savedm", macMainpSbruan.getSavedm());
            valuesMap.put("addr", macMainpSbruan.getAddr());
            valuesMap.put("date", date);
            String templateString = macMainpSbruan.getMenuSql();


            ExpressionParser parser = new SpelExpressionParser();
            TemplateParserContext parserContext = new TemplateParserContext();
            String content = parser.parseExpression(templateString, parserContext).getValue(valuesMap, String.class);
            List<WeekMenuBakDto> weekMenuBakDtoList = drPublicMapper.getWeekMenuDtoSql(content);
//            List<WeekMenuBakDto> weekMenuBakDtoList = drPublicMapper.getWeekMenuDto(macMainpSbruan.getMenuTable(),
//                    macMainpSbruan.getSavedm(), date, macMainpSbruan.getAddr());
            int i = 1;
            for (WeekMenuBakDto goo : weekMenuBakDtoList) {
                goo.setZl(ObjectUtil.getStr(goo.getZl()));
                goo.setName(ObjectUtil.getStr(goo.getName()));
                goo.setBm(ObjectUtil.getStr(goo.getBm()));
                goo.setDinner(ObjectUtil.getStr(goo.getDinner()));
                MacMainpFoodMenu macMainpFoodMenu = foodMenuList.stream()
                        .filter(v -> ObjectUtil.getStr(v.getCode()).equals(goo.getBm()))
                        .findFirst().orElse(null);
                if(macMainpFoodMenu == null) {
                    MacMainpFoodMenu foodMenu = new MacMainpFoodMenu();
                    try {
                        foodMenu.setCardId(ObjectUtil.getStr(goo.getXh()));
                    } catch (Exception e) {
                        foodMenu.setCardId("0");
                    }
                    foodMenu.setCode(goo.getBm());
                    foodMenu.setZl(goo.getZl());
                    foodMenu.setAddr(goo.getAddr());
                    foodMenu.setName(goo.getName());
                    foodMenu.setPrice(goo.getPrice());
                    foodMenu.setId(i++);
                    foodMenuList.add(foodMenu);
                }
            }
            jsonObject.put("weekMenuBak", weekMenuBakDtoList);
        } catch (Exception e) {
            e.printStackTrace();
        }


        List<MacMainpSbruanDinner> macMainpSbruanDinnerList = macMainpSbruanDinnerService.list(new QueryWrapper<MacMainpSbruanDinner>().lambda()
                .eq(MacMainpSbruanDinner::getDeviceId, macMainpSbruan.getId()));
        jsonObject.put("macMainpSbruanDinnerList", macMainpSbruanDinnerList);

        /*List<MacMainpFoodMenu> macMainpFoodMenuList = macMainpFoodMenuService.list(new QueryWrapper<MacMainpFoodMenu>()
                .lambda().eq(MacMainpFoodMenu::getAddr,macMainpSbruan.getAddr()));*/
        jsonObject.put("macMainpFoodMenuList", foodMenuList);

        result.setResult(GZip.gzip(jsonObject.toString()));
        return result;
    }


}
